package actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

import org.apache.struts.action.*;


public class LogonAction extends Action 
{
	public ActionForward execute(ActionMapping mapping, ActionForm form, 
		    HttpServletRequest request, HttpServletResponse response) {
		
		forms.LogonForm lo = (forms.LogonForm) form;
		
		
		
		String uname = (String) request.getSession().getAttribute("uname");
		lo.setUname(uname);
		System.out.println("uname = " + uname);
		
		
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		boolean ret = false;

		
		try {
			// Registering Postgresql JDBC driver
			Class.forName("org.postgresql.Driver");
			// Open a connection to the database	
			conn = DriverManager.getConnection("jdbc:postgresql://localhost/cse135?" +
			        "user=postgres&password=password");
			// Create the statement
		    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
		                				ResultSet.CONCUR_UPDATABLE);
			
			rs = stmt.executeQuery("SELECT user_name,APP FROM users WHERE user_name = '" + uname + "'");
			while( rs.next() )
			{
				if( rs.getInt("APP") > 0 )
				{
					System.out.println("reached one:" + rs.getInt("APP"));
					ret = true;
				}
				else
				{
					//System.out.println("reached two");
					ret = false;
				}
			}
			
			// close connection
			rs.close();
			stmt.close();
			conn.close();
			
		} catch (SQLException e) 
		{ 
			System.out.println(e);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		if (!ret) {	

			return (mapping.findForward("newApplicant"));	
		}
		else {	
			//System.out.println("return");
		    return (mapping.findForward("retApplicant"));	
		}
	}
}

